﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SalesPages.Service.Cache.Redis
{
    public class RedisManager
    {
        private static  IDatabase _db;
        private static  ConnectionMultiplexer _redis;
        private static  RedisConfigInfo _configInfo;
        private static ConfigurationOptions config;
        const string configuration = "{0},abortConnect=false,defaultDatabase={1},ssl=false,ConnectTimeout={2},allowAdmin=true,connectRetry={3}";

        private static Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>(() => Create(), LazyThreadSafetyMode.PublicationOnly);
       
        private static ConnectionMultiplexer Create()
        {
            _configInfo = RedisConfigInfo.GetConfig();

            config = ConfigurationOptions.Parse(string.Format(configuration, _configInfo.ServerList,
                    _configInfo.DefaultDB, _configInfo.ConnectTimeout,
                    _configInfo.ConnectRetry));

            _redis = ConnectionMultiplexer
                .Connect(config);

            _redis.PreserveAsyncOrder = _configInfo.PreserveAsyncOrder;
            //_redis.ConnectionFailed;
           return _redis;

        }

        public static ConnectionMultiplexer Connection
        {
            get { return LazyConnection.Value; }
        }
    }
}
